package day01;

import java.util.Arrays;

/**
 * @author Jetwang
 * @version 1.0
 * @since 2023/3/13 21:02
 * 选择排序
 */
public class ChooseSort {
    public static void main(String[] args) {
        int[] arr = {2, 4, 1, 5, 3, 9, 7, 6, 8};
        System.out.println("排序前:" + Arrays.toString(arr));
        chooseSort(arr);
        System.out.println("排序后:" + Arrays.toString(arr));
    }

    /**
     * 选择排序  不稳定排序
     * @param arr
     */
    public static void chooseSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            int idx = i;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[idx] > arr[j]) {
                    idx = j;
                }
            }
            swap(arr, idx, i);
        }
    }

    static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}
